//
//  LLNWReachability.m
//  LLFoundation
//
//  Created by my_liu on 2016/11/14.
//  Copyright © 2016年 . All rights reserved.
//

#import "LLNWReachability.h"
#import "Reachability.h"

@interface LLNWReachability ()
{
    Reachability * _reachability;
}
@end

@implementation LLNWReachability

- (instancetype)initWithDefault
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
        _reachability = [Reachability reachabilityForInternetConnection];
    }
    return self;
}

- (instancetype)initWithDomain:(NSString *)domain
{
    self = [super init];
    if(self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
        _reachability = [Reachability reachabilityWithHostName:domain];
    }
    return self;
}

- (id)initWithAddress:(void *)hostAddress
{
    self = [super init];
    if(self){
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
        
        _reachability = [Reachability reachabilityWithAddress:hostAddress];
        
    }
    return self;
}

- (void)reachabilityChanged:(NSNotification *)notification
{
    [[NSNotificationCenter defaultCenter] postNotificationName:LLNWReachabilityDidChangeNotification object:self];
}

- (void)startMonitoring
{
    [_reachability startNotifier];
}
- (void)stopMonitoring
{
    [_reachability  stopNotifier];
}

- (LLNWReachabilityStatus)networkReachabilityStatus
{
    LLNWReachabilityStatus  cuState = LLNWReachabilityStatusUnknown;
    
    NetworkStatus status = [_reachability  currentReachabilityStatus];
    
    switch (status) {
        case NotReachable:
        {
            cuState = LLNWReachabilityStatusNotReachable;
            break;
            
        }
        case ReachableViaWiFi:
        {
            cuState = LLNWReachabilityStatusReachableViaWiFi;
            break;
        }
        case ReachableViaWWAN:
        {
            cuState = LLNWReachabilityStatusReachableViaWWAN;
            break;
        }
        default:
            break;
    }
    
    return cuState;
    
}

- (BOOL)isReachable
{
    return [_reachability isReachable];
}

- (BOOL)isReachableViaWWAN
{
    return [_reachability isReachableViaWWAN];
}

- (BOOL)isReachableViaWiFi
{
    return [_reachability isReachableViaWiFi];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
}

@end
